import os

import oss2

# 配置信息
ACCESS_KEY_ID = 'LTAI5tNFRqGpg2e4MPW6isse'
ACCESS_KEY_SECRET = 'ZDqMf735QUa3vTXLHcHEFzV1HSJ5KT'
BUCKET_NAME = 'qulai-upload-consloe'
ENDPOINT = 'oss-cn-shenzhen.aliyuncs.com'
DIST_DIR = r'C:\code\vue\kuajing-vue\dist'  # Vue应用的打包输出文件夹路径
import mimetypes


def get_content_type(file_path):
    """根据文件路径获取内容类型"""
    content_type, _ = mimetypes.guess_type(file_path)
    if content_type is None:
        # 如果无法猜测，则默认为二进制流
        return 'application/octet-stream'
    return content_type


def upload_to_oss(bucket_name, endpoint, access_key_id, access_key_secret, local_dir):
    # 创建Bucket对象
    auth = oss2.Auth(access_key_id, access_key_secret)
    bucket = oss2.Bucket(auth, endpoint, bucket_name)

    print(f"Uploading files from {local_dir} to OSS bucket {bucket_name}...")

    for root, dirs, files in os.walk(local_dir):
        for file in files:
            local_path = os.path.join(root, file)
            relative_path = os.path.relpath(local_path, local_dir).replace("\\", "/")  # Windows兼容性处理

            # 获取文件的Content-Type
            content_type = get_content_type(local_path)

            # 如果是index.html文件，强制设置Content-Type为text/html
            if relative_path.lower() == "index.html":
                content_type = "text/html"
                # 确保 Content-Disposition 不设置为 attachment
                headers = {'Content-Type': content_type, 'Content-Disposition': 'inline', "x-oss-force-download": 'false'}
            else:
                headers = {'Content-Type': content_type}

            print(f"Uploading {relative_path} with Content-Type: {content_type}...")
            with open(local_path, 'rb') as fileobj:
                bucket.put_object(relative_path, fileobj, headers=headers)

    print("Upload completed.")


if __name__ == '__main__':
    upload_to_oss(BUCKET_NAME, ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET, DIST_DIR)
